const dayjs = require('dayjs')
const db = require('../db/index')
const createExcel = require('../js/exceljs')
// 获取所有车的品牌
exports.carBrandList = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  const sql = `select * from carbrand where appid=? ORDER BY sort ASC limit ${size} OFFSET  ${from}`
  db.query(sql, [appid, pageData.carOwnerId], (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from carbrand where appid=? `
    db.query(sql2, [appid, pageData.carOwnerId], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 获取车辆详情
exports.carDetils = (req, res) => {
  const data = req.body
  const sql = 'select * from carbrand where _id = ? and appid=?'
  db.query(sql, [data.carId, data.appid], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2[0],
    })
  })
}
// 删除车型
exports.carBrandDelete = (req, res) => {
  let data = req.body
  let sql = `delete from carbrand where _id=?`
  db.query(sql, [data.id], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      message: '删除成功',
      type: 1
    })
  })
}
// 添加车型
exports.carBrandAdd = (req, res) => {
  let data = req.body
  data.A3 = []
  data.A5 = []
  data.A7 = []
  data.A8 = []
  try {
    data.remark = data.remark.split(',').map((item) => {
      return item.split('-')
    })
    data.remark.forEach((item) => {
      data[item[1]].push(item[0])
    })
    delete data.remark
    data.A3 = JSON.stringify(data.A3)
    data.A5 = JSON.stringify(data.A5)
    data.A7 = JSON.stringify(data.A7)
    data.A8 = JSON.stringify(data.A8)
    let selectSql = `select * from carbrand where appid=? and name=?`
    db.query(selectSql, [data.appid, data.name], (err, res3) => {
      if (err) return res.cc(err)
      if (res3.length == 0) {
        let sql = `insert into carbrand set ?`
        db.query(sql, data, (err, res3) => {
          if (err) return res.cc(err)
          res.send({
            message: '添加成功',
            type: 1
          })
        })
      } else {
        res.send({
          message: '品牌重复',
          type: 2
        })
      }
    })
  } catch (error) {
    res.send({
      message: '型号格式错误',
      type: 2
    })
  }
}
// 编辑
exports.carBrandChange = (req, res) => {
  let data = req.body
  data.A3 = []
  data.A5 = []
  data.A7 = []
  data.A8 = []
  try {
    data.remark = data.remark.split(',').map((item) => {
      return item.split('-')
    })
    data.remark.forEach((item) => {
      data[item[1]].push(item[0])
    })
    delete data.remark
    data.A3 = JSON.stringify(data.A3)
    data.A5 = JSON.stringify(data.A5)
    data.A7 = JSON.stringify(data.A7)
    data.A8 = JSON.stringify(data.A8)
    let sql = `update carbrand set ? where _id=?`
    db.query(sql, [data, data._id], (err, res3) => {
      if (err) return res.cc(err)
      res.send({
        message: '修改成功',
        type: 1
      })
    })
  } catch (error) {
    res.send({
      message: '型号格式错误',
      type: 2
    })
  }
}
// 搜索
exports.carBrandSerach = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  pageData.name = pageData.name ? pageData.name : ''
  pageData.carType = pageData.carType ? pageData.carType : ''
  const sql = `select * from carbrand where appid=${appid}  and name like "%${pageData.name}%" and (A3 like "%${pageData.carType}%" or A5 like "%${pageData.carType}%" or A7 like "%${pageData.carType}%")  limit ${size} OFFSET  ${from}`
  db.query(sql, (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from carbrand where appid=? and name like "%${pageData.name}%" and (A3 like "%${pageData.carType}%" or A5 like "%${pageData.carType}%" or A7 like "%${pageData.carType}%")`
    db.query(sql2, [appid], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 导出信息
exports.carBrandCreateExcel = (req, res) => {
  let data = req.body
  columns = [
    { header: '品牌图片', key: '', width: 10, height: 10 },
    { header: '车辆品牌', key: 'name' },
    { header: 'A3', key: 'A3' },
    { header: 'A5', key: 'A5' },
    { header: 'A7', key: 'A7' },
  ]
  let sql = ``
  if (data.id == 'all') {
    sql = 'select * from carbrand where appid=?'
  } else {
    sql = 'select * from carbrand where appid=? and _id in (?)'
  }
  db.query(sql, [data.appid, data.id], async (err, res2) => {
    if (err) return res.cc(err)
    const buffer = await createExcel.createExcel(columns, res2, 'image')
    res.setHeader('Content-disposition', 'attachment; filename=download.xlsx')
    res.setHeader('Content-type', 'application/octet-stream')
    res.send(buffer)
  })
}
// 车型号进行排序
exports.carBrandSort = (req, res) => {
  let data = req.body
  try {
    data.id.forEach((item, index) => {
      const sql = `update carbrand set sort=? where _id = ?`
      db.query(sql, [data.sort[index], item], (err, res2) => {
        if (err) throw Error(err)
      })
    })
    res.send({
      message: '排序成功'
    })
  } catch (error) {
    return res.cc(error)
  }

}
// 获取膜列表
exports.filmList = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  const sql = `select * from film where appid=? limit ${size} OFFSET  ${from}`
  db.query(sql, [appid], (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from film where appid=? `
    db.query(sql2, [appid], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 添加膜
exports.filmListAdd = (req, res) => {
  let data = req.body
  data.usableStore = JSON.stringify(data.usableStore)
  data.usableStoreName = JSON.stringify(data.usableStoreName)
  const sql = `insert into film set ?`
  db.query(sql, [data], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      message: '添加成功',
      type: 1
    })
  })
}
// 删除膜
exports.filmListDelete = (req, res) => {
  let data = req.body
  const sql = `delete from film where _id=?`
  db.query(sql, [data.id], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      message: '添加成功',
      type: 1
    })
  })
}
// 修改车膜
exports.filmListChange = (req, res) => {
  let data = req.body
  data.usableStore = JSON.stringify(data.usableStore)
  data.usableStoreName = JSON.stringify(data.usableStoreName)
  const sql = `update film set ? where _id=?`
  db.query(sql, [data, data._id], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      message: '修改成功',
      type: 1
    })
  })
}

// 导出膜的信息
exports.filmCreateExcel = (req, res) => {
  let data = req.body
  columns = [
    { header: '产品类型', key: 'type' },
    { header: '产品型号', key: 'name' },
    { header: '质保年限', key: 'age' },
    { header: '使用次数', key: 'countAll' },
    { header: '使用权限', key: 'authority' },
    { header: '可用门店', key: 'usableStoreName' },
    { header: 'A3车价格', key: 'A3Price' },
    { header: 'A5车价格', key: 'A5Price' },
    { header: 'A7车价格', key: 'A7Price' },
    { header: 'A8车价格', key: 'A8Price' },
  ]
  let sql = ``
  if (data.id == 'all') {
    sql = 'select * from film where appid=?'
  } else {
    sql = 'select * from film where appid=? and _id in (?)'
  }
  db.query(sql, [data.appid, data.id], async (err, res2) => {
    if (err) return res.cc(err)
    const buffer = await createExcel.createExcel(columns, res2)
    res.setHeader('Content-disposition', 'attachment; filename=download.xlsx')
    res.setHeader('Content-type', 'application/octet-stream')
    res.send(buffer)
  })
}
// 膜搜索
exports.filmSerach = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  pageData.type = pageData.type ? pageData.type : ''
  pageData.name = pageData.name ? pageData.name : ''
  pageData.authority = pageData.authority ? pageData.authority : ''
  pageData.usableStoreName = pageData.usableStoreName ? pageData.usableStoreName : ''
  const sql = `select * from film where appid=${appid}  and (name like "%${pageData.name}%" and type like "%${pageData.type}%" and authority like "%${pageData.authority}%" and usableStoreName like "%${pageData.usableStoreName}%")  limit ${size} OFFSET  ${from}`
  db.query(sql, (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from film where appid=? and (name like "%${pageData.name}%" and type like "%${pageData.type}%" and authority like "%${pageData.authority}%" and usableStoreName like "%${pageData.usableStoreName}%")`
    db.query(sql2, [appid], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 根据条件筛选膜
exports.filmListSelect = (req, res) => {
  let pageData = req.body
  pageData.usableStore = pageData.storeId ? JSON.stringify(pageData.storeId) : ''
  pageData.type = pageData.filmType ? pageData.filmType : ''
  pageData.province = pageData.region ? pageData.region : ''
  const sql = `select * from film where appid=${pageData.appid}  and ((usableStore like "%?%" or usableStore like "%all%") and type like "%${pageData.type}%" and province like "%${pageData.province}%")`
  db.query(sql, [pageData.usableStore], (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from film where appid=? and ((usableStore like "%?%" or usableStore like "all")  and type like "%${pageData.type}%" and province like "%${pageData.province}%")`
    db.query(sql2, [pageData.usableStore, pageData.appid], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 根据条件筛选膜表格发货用
exports.filmListSelectExcel = (req, res) => {
  let pageData = req.body
  const sql = `select * from film where appid=${pageData.appid} and nameNumber=?`
  db.query(sql, [pageData.nameNumber], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2[0],
    })
  })
}
// 根据条件筛选膜小程序
exports.filmTypeSamll = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid

  const sql = `select * from film where appid=? and type=? limit ${size} OFFSET  ${from} `
  db.query(sql, [appid, pageData.type], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2,
    })
  })
}
// 根据条件筛选可用膜 小程序
exports.filmTypeSamll2 = (req, res) => {
  let pageData = req.body
  const sql = `select * from film where appid=? and type=? and(usableStore like "%all%" or usableStore like "%${pageData.storeId}%")`
  db.query(sql, [pageData.appid, pageData.type], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2,
    })
  })
}
// 获取膜详情小程序
exports.filmTypeDetilsSamll = (req, res) => {
  let pageData = req.body
  let appid = pageData.appid

  const sql = `select * from film where appid=? and _id=? `
  db.query(sql, [appid, pageData.filmId], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2[0],
    })
  })
}